<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>哔哩哔哩创作中心 - 评论管理</title>
    <link rel="stylesheet" href="css/all.min.css">
    <link rel="icon" sizes="any" href="img/favicon.ico">
    <link rel="stylesheet" type="text/css" href="css/commentManagement.css">
</head>

<body>
    <!-- 左侧导航栏 -->
    <div class="sidebar">
        <div class="logo">
            <img src="img/favicon.ico" alt="Bilibili">
            <div class="logo-text">创作中心</div>
        </div>

        <!-- 投稿按钮 -->
        <button id="uploadBtn" class="upload-btn">
            <i class="fas fa-plus"></i>
            <span>投稿</span>
        </button>

        <!-- 修改后的导航项 -->
        <a href="createCenter.html" class="nav-item" data-target="home">
            <i class="fas fa-home"></i>
            <span>首页</span>
        </a>
        <a href="contributionManagement.html" class="nav-item" data-target="video">
            <i class="fas fa-file-video"></i>
            <span>稿件管理</span>
        </a>
        <!-- 这是评论管理链接 -->
        <a href="#" class="nav-item active" data-target="comment">
            <i class="fas fa-comments"></i>
            <span>评论管理</span>
        </a>
        <!-- 这是弹幕管理链接 -->
        <a href="danmakuManagement.html" class="nav-item" data-target="danmaku">
            <i class="fas fa-closed-captioning"></i>
            <span>弹幕管理</span>
        </a>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
        <!-- 顶部工具栏 -->
        <div class="top-bar">
            <div class="search-box">
                <a href="index.html" style="text-decoration: none;color: #00A1D6;">
                    <span class="span1">
                        <svg width="18" height="18" viewBox="0 0 18 18" fill="none"
                            xmlns="http://www.w3.org/2000/svg" class="zhuzhan-icon">
                            <path fill-rule="evenodd" clip-rule="evenodd"
                                d="M3.73252 2.67094C3.33229 2.28484 3.33229 1.64373 3.73252 1.25764C4.11291 0.890684 4.71552 0.890684 5.09591 1.25764L7.21723 3.30403C7.27749 3.36218 7.32869 3.4261 7.37081 3.49407H10.5789C10.6211 3.4261 10.6723 3.36218 10.7325 3.30403L12.8538 1.25764C13.2342 0.890684 13.8368 0.890684 14.2172 1.25764C14.6175 1.64373 14.6175 2.28484 14.2172 2.67094L13.364 3.49407H14C16.2091 3.49407 18 5.28493 18 7.49407V12.9996C18 15.2087 16.2091 16.9996 14 16.9996H4C1.79086 16.9996 0 15.2087 0 12.9996V7.49406C0 5.28492 1.79086 3.49407 4 3.49407H4.58579L3.73252 2.67094ZM4 5.42343C2.89543 5.42343 2 6.31886 2 7.42343V13.0702C2 14.1748 2.89543 15.0702 4 15.0702H14C15.1046 15.0702 16 14.1748 16 13.0702V7.42343C16 6.31886 15.1046 5.42343 14 5.42343H4ZM5 9.31747C5 8.76519 5.44772 8.31747 6 8.31747C6.55228 8.31747 7 8.76519 7 9.31747V10.2115C7 10.7638 6.55228 11.2115 6 11.2115C5.44772 11.2115 5 10.7638 5 10.2115V9.31747ZM12 8.31747C11.4477 8.31747 11 8.76519 11 9.31747V10.2115C11 10.7638 11.4477 11.2115 12 11.2115C12.5523 11.2115 13 10.7638 13 10.2115V9.31747C13 8.76519 12.5523 8.31747 12 8.31747Z"
                                fill="currentColor"></path>
                        </svg>
                    </span>
                    <span class="span2" style="vertical-align: top;">首页</span>
                </a>
            </div>

            <div class="user-actions">
                <div class="notification">
                    <i class="fas fa-bell"></i>
                </div>
                <div class="user-profile">
                    <div class="user-avatar">UP</div>
                    <div class="username">创作UP主</div>
                </div>
            </div>
        </div>

        <!-- 评论管理内容区域 -->
        <div class="content-area">
            <h1 class="section-title"><i class="fas fa-comments"></i> 评论管理</h1>

            <div class="comment-management">
                <!-- 评论工具栏 -->
                <div class="comment-tools">
                    <div class="filter-group">
                        <span class="filter-label">视频:</span>
                        <div class="search-box">
                            <i class="fas fa-search"></i>
                            <input type="text" placeholder="搜索评论内容"  id="commentSearch">
                        </div>
                    </div>

                    <div class="filter-group">
                        <span class="filter-label">排序:</span>
                        <select class="filter-select" id="commentSort">
                            <option value="newest">最新优先</option>
                            <option value="oldest">最早优先</option>
                        </select>
                    </div>

                    <div class="action-buttons">
                        <button class="action-btn primary" id="refresh-comments">
                            <i class="fas fa-sync-alt"></i> 刷新
                        </button>
                    </div>
                </div>

                <!-- 评论列表 -->
                <div class="comment-list" id="comment-list">

                </div>

                <!-- 分页控件 -->
                <div class="pagination" id="pagination">
                    <button class="pagination-btn disabled" id="prev-page">
                        <i class="fas fa-chevron-left"></i>
                    </button>
                    <button class="pagination-btn active" data-page="1">1</button>
                    <button class="pagination-btn">2</button>
                    <button class="pagination-btn">3</button>
                    <button class="pagination-btn">4</button>
                    <button class="pagination-btn">5</button>
                    <button class="pagination-btn">
                        <i class="fas fa-ellipsis-h"></i>
                    </button>
                    <button class="pagination-btn">10</button>
                    <button class="pagination-btn" id="next-page">
                        <i class="fas fa-chevron-right"></i>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 投稿模态框 -->
    <div id="uploadModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <div class="modal-title">投稿新视频</div>
                <button class="close-btn">&times;</button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label for="videoTitle">视频标题</label>
                    <input type="text" id="videoTitle" placeholder="输入视频标题">
                </div>

                <div class="form-group">
                    <label for="videoDesc">视频简介</label>
                    <textarea id="videoDesc" placeholder="输入视频简介"></textarea>
                </div>

                <div class="form-group">
                    <label for="videoCategory">视频分区</label>
                    <select id="videoCategory">
                        <option value="">选择视频分区</option>
                        <option value="game">游戏</option>
                        <option value="music">音乐</option>
                        <option value="knowledge">知识</option>
                        <option value="tech">科技</option>
                        <option value="life">生活</option>
                        <option value="entertainment">娱乐</option>
                    </select>
                </div>

                <div class="form-group">
                    <label>上传视频文件</label>
                    <div class="file-upload" id="videoUpload">
                        <i class="fas fa-cloud-upload-alt"></i>
                        <p>点击或拖拽文件到此处上传</p>
                        <p class="small">支持MP4、MOV、AVI等格式，最大2GB</p>
                    </div>
                </div>

                <div class="form-group">
                    <label>上传封面图片</label>
                    <div class="file-upload" id="coverUpload">
                        <i class="fas fa-image"></i>
                        <p>点击或拖拽文件到此处上传</p>
                        <p class="small">支持JPG、PNG格式，建议尺寸1146x717</p>
                    </div>
                </div>
                <input type="hidden" id="durationInSeconds" name="durationInSeconds">
            </div>
            <div class="modal-footer">
                <button class="btn-submit" id="btn-submit">发布投稿</button>
            </div>
        </div>
    </div>

    
    <script src="js/jquery.js">

    </script>
    <script>
    let userNameB = $(".username")
    let avatar = $(".user-avatar")
    $.ajax({
    	url:"userSession",
    	type:"post",
    	success:function(data){
    		if(data.code == 200){
    			userNameB.text(data.data.nickname)
    			avatar.css({
    				"background-image":"url("+data.data.avatarUrl+")",
    				"background-size":"cover"
    			})
    			avatar.text("")
    		}
    	}
    })
    // 全局变量存储文件对象
    let videoFile = null;
    let coverFile = null;
    let isFormSubmitInitialized = false;
    let isNavigationInitialized = false;
    let isModalInitialized = false;
    let currentPage = 1;
    let comments = [];
    let filteredComments = []; // 存储过滤后的评论
    let currentSort = 'newest'; // 当前排序方式
    const itemsPerPage = 5;
	
 // 初始化文件上传区域
    function initFileUploads() {
        // 创建并缓存文件输入元素
        const videoFileInput = document.getElementById('videoFileInput') || createFileInput('videoUpload');

        
        const coverFileInput = document.getElementById('coverFileInput') || createFileInput('coverUpload');
        
        // 获取上传区域
        const videoUpload = document.getElementById('videoUpload');
        const coverUpload = document.getElementById('coverUpload');
        
        // 防止重复绑定事件
        if (!videoUpload._initialized) {
            // 设置拖放功能
            setupDragDrop(videoUpload, videoFileInput, 'video');
            setupDragDrop(coverUpload, coverFileInput, 'image');
            
            // 设置点击功能
            videoUpload.addEventListener('click', () => videoFileInput.click());
            coverUpload.addEventListener('click', () => coverFileInput.click());
            
            // 监听文件选择变化
            videoFileInput.addEventListener('change', () => handleFileSelection(videoFileInput, videoUpload, 'video'));
            coverFileInput.addEventListener('change', () => handleFileSelection(coverFileInput, coverUpload, 'image'));
            
            // 标记为已初始化
            videoUpload._initialized = true;
            coverUpload._initialized = true;
        }
    }

    // 创建隐藏的文件输入元素
    function createFileInput(id) {
        const input = document.createElement('input');
        input.type = 'file';
        input.id = `${id}Input`;
        input.style.display = 'none';
        input.accept = id === 'videoUpload' ? 'video/*' : 'image/*';
        document.body.appendChild(input);
        return input;
    }

    // 设置拖放功能
    function setupDragDrop(uploadArea, fileInput, type) {
        uploadArea.addEventListener('dragover', function(e) {
            e.preventDefault();
            this.style.borderColor = '#00A1D6';
            this.style.backgroundColor = 'rgba(0, 161, 214, 0.1)';
        });

        uploadArea.addEventListener('dragleave', function() {
            this.style.borderColor = '';
            this.style.backgroundColor = '';
        });

        uploadArea.addEventListener('drop', function(e) {
            e.preventDefault();
            this.style.borderColor = '';
            this.style.backgroundColor = '';

            if (e.dataTransfer.files.length) {
                fileInput.files = e.dataTransfer.files;
                handleFileSelection(fileInput, uploadArea, type);
            }
        });
    }

    // 处理文件选择
    function handleFileSelection(fileInput, uploadArea, type) {
        if (fileInput.files.length) {
            const file = fileInput.files[0];
            
            // 更新全局变量
            if (type === 'video') {
                videoFile = file;
                uploadArea.innerHTML = `
                    <i class="fas fa-check-circle" style="color:#4CAF50;"></i>
                    <p>${file.name}</p>
                    <p class="small">计算时长中...</p>
                `;
                getVideoDuration(file).then(duration => {
                	const durationInSeconds = Math.floor(duration);
                    console.log('视频时长（秒）:', durationInSeconds);
                    // 确保设置到隐藏字段
                    document.getElementById('durationInSeconds').value = durationInSeconds;
                    // 更新UI显示时长
                    uploadArea.innerHTML = `
                        <i class="fas fa-check-circle" style="color:#4CAF50;"></i>
                        <p>${file.name}</p>
                        <p class="small">时长: ${formatDuration(duration)}</p>
                        <p class="small" style="color:#4CAF50;">视频已选择</p>
                    `;
                }).catch(error => {
                    console.error('获取视频时长失败:', error);
                    document.getElementById('durationInSeconds').value = 0;
                    uploadArea.innerHTML = `
                        <i class="fas fa-check-circle" style="color:#4CAF50;"></i>
                        <p>${file.name}</p>
                        <p class="small" style="color:#FF5722;">时长计算失败</p>
                        <p class="small" style="color:#4CAF50;">视频已选择</p>
                    `;   
                });
            } else {
            	coverFile = file;
            	uploadArea.innerHTML = `
                    <i class="fas fa-check-circle" style="color:#4CAF50;"></i>
                    <p>${file.name}</p>
                    <p class="small" style="color:#4CAF50;">封面已选择</p>
                `;
            }
            
            // 更新UI显示
            uploadArea.innerHTML = `
                <i class="fas fa-check-circle" style="color:#4CAF50;"></i>
                <p>${file.name}</p>
                <p class="small" style="color:#4CAF50;">${type === 'video' ? '视频' : '封面'}已选择</p>
            `;
            
            // 重新绑定点击事件（因为innerHTML会移除原有的事件监听器）
            const fileInputEl = document.getElementById(`${uploadArea.id}Input`);
            uploadArea.addEventListener('click', () => fileInputEl.click());
        }
    }
    function getVideoDuration(file) {
    	return new Promise((resolve, reject) => {
            const video = document.createElement('video');
            const url = URL.createObjectURL(file);
            
            video.onloadedmetadata = () => {
                URL.revokeObjectURL(url); // 释放内存
                if (video.duration && video.duration > 0) {
                    resolve(video.duration);
                } else {
                    reject(new Error('无法获取有效视频时长'));
                }
            };
            
            video.onerror = () => {
                URL.revokeObjectURL(url);
                reject(new Error('视频加载失败'));
            };
            
            video.src = url;
            
            // 设置超时处理
            setTimeout(() => {
                if (video.readyState >= 1 && video.duration > 0) {
                    URL.revokeObjectURL(url);
                    resolve(video.duration);
                } else {
                    URL.revokeObjectURL(url);
                    reject(new Error('获取视频时长超时'));
                }
            }, 5000); // 5秒超时
        });
    }

    // 新增：格式化时长的函数
    function formatDuration(seconds) {
        const h = Math.floor(seconds / 3600);
        const m = Math.floor((seconds % 3600) / 60);
        const s = Math.floor(seconds % 60);
        
        if (h > 0) {
            return `${h}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
        } else {
            return `${m}:${s.toString().padStart(2, '0')}`;
        }
    }

    // 初始化表单提交（防止重复绑定）
    function initFormSubmit() {
    if (isFormSubmitInitialized) return;
        
        $("#btn-submit").off('click.submitHandler').on('click.submitHandler', function(e) {
            e.preventDefault();
            
            // 验证表单
            if (!videoFile) {
                alert('请选择视频文件');
                return;
            }
            
            // 确保获取时长值
            const durationInSeconds = document.getElementById('durationInSeconds').value || 0;
            
            const formData = new FormData();
            
            // 添加文本字段
            formData.append('videoTitle', $('#videoTitle').val());
            formData.append('videoDesc', $('#videoDesc').val());
            formData.append('videoCategory', $('#videoCategory').val());
            formData.append('durationInSeconds', durationInSeconds); // 明确添加时长字段
            
            // 添加文件
            formData.append('videoFile', videoFile);
            if (coverFile) formData.append('coverFile', coverFile);
            // 发送Ajax请求
            $.ajax({
                type: "POST",
                url: "createCenter.do",
                data: formData,
                contentType: false,
                processData: false,
                beforeSend: function() {
                    $("#btn-submit").html('<i class="fas fa-spinner fa-spin"></i> 上传中...').prop('disabled', true);
                },
                success: function(data) {
                    console.log("上传成功:", data);
                    alert('投稿成功！');
                    uploadModal.style.display = 'none';
                    document.body.style.overflow = 'auto';
                    resetUploadForm();
                },
                error: function(xhr, status, error) {
                    console.error("上传失败:", error);
                    alert('投稿失败：' + (xhr.responseJSON ? xhr.responseJSON.message : '网络错误'));
                },
                complete: function() {
                    $("#btn-submit").html('发布投稿').prop('disabled', false);
                }
            });
        });
        
        isFormSubmitInitialized = true;
    }

    // 重置上传表单
    function resetUploadForm() {
        videoFile = null;
        coverFile = null;
        
        // 重置UI显示
        $('#videoUpload').html(`
            <i class="fas fa-cloud-upload-alt"></i>
            <p>点击或拖拽视频到此处</p>
            <p class="small">支持MP4、MOV、AVI等格式，最大2GB</p>
        `);
        
        $('#coverUpload').html(`
            <i class="fas fa-image"></i>
            <p>点击或拖拽封面到此处</p>
            <p class="small">支持JPG、PNG格式，建议尺寸1146x717</p>
        `);
        
        // 清空表单字段
        $('#videoTitle').val('');
        $('#videoDesc').val('');
        $('#videoCategory').val('');
    }

    // 初始化导航栏交互（防止重复绑定）
    function initNavigation() {
        if (isNavigationInitialized) return;
        
        const navItems = document.querySelectorAll('.nav-item');
        navItems.forEach(item => {
            item.removeEventListener('click', handleNavClick);
            item.addEventListener('click', handleNavClick);
        });
        
        isNavigationInitialized = true;
    }

    // 导航栏点击处理函数
    function handleNavClick(e) {
        const navItems = document.querySelectorAll('.nav-item');
        navItems.forEach(nav => nav.classList.remove('active'));
        this.classList.add('active');

        // 更新页面标题
        const title = this.querySelector('span').textContent;
        document.querySelector('.section-title').innerHTML =
            `<i class="${this.querySelector('i').className}"></i> ${title}`;
    }

    // 初始化模态框交互（防止重复绑定）
    function initModal() {
        if (isModalInitialized) return;
        
        const uploadBtn = document.getElementById('uploadBtn');
        const uploadModal = document.getElementById('uploadModal');
        const closeBtn = document.querySelector('.close-btn');

        $(uploadBtn).off('click.modal').on('click.modal', function() {
            uploadModal.style.display = 'flex';
            document.body.style.overflow = 'hidden';
        });

        $(closeBtn).off('click.modal').on('click.modal', function() {
            uploadModal.style.display = 'none';
            document.body.style.overflow = 'auto';
        });

        $(window).off('click.modal').on('click.modal', function(event) {
            if (event.target === uploadModal) {
                uploadModal.style.display = 'none';
                document.body.style.overflow = 'auto';
            }
        });
        
        isModalInitialized = true;
    }
    document.addEventListener('DOMContentLoaded', function() {
        console.log('DOMContentLoaded事件触发');
        initFileUploads();
        initFormSubmit();
        initNavigation();
        initModal();
        allVideo(); // 加载视频
        showLatestComments(); // 加载最新评论
        
        // 额外添加定时刷新评论（测试用）
        setInterval(showLatestComments, 5000); // 每5秒刷新一次
    });
    showViewCount();
    function showViewCount(){
    	$.ajax({
            type: "GET",
            url: "allViewCount.do",
            data: {
            	
            },
            success: function(data) {
            	$("#viewCount").append(data.data);
            }
            
        });
    	
    }
    showFollowerCount();
    function showFollowerCount(){
    	$.ajax({
            type: "GET",
            url: "allFollowerCount.do",
            data: {
            	
            },
            success: function(data) {
            	$("#followerCount").append(data.data);
            }
            
        });
    	
    }
    function queryCommentCount(videoId) {
        return new Promise((resolve, reject) => {
            $.ajax({
                type: "GET",
                url: "oneComment.do",
                data: { e: videoId },
                success: function(data) {
                    resolve(data.data);
                },
                error: function(error) {
                    console.error("获取评论数失败:", error);
                    resolve(0); // 失败时返回0
                }
            });
        });
    }
    async function allVideo() {
        try {
            const videoResponse = await $.ajax({
                type: "GET",
                url: "allVideo.do"
            });

            const videoData = videoResponse.data;
            const videoContainer = $("#video-manage");
            videoContainer.empty();

            // 限制只显示5个视频
            const videosToShow = videoData.slice(0, 5);
            
            const videoItems = await Promise.all(videosToShow.map(async video => {
                const commentCount = await queryCommentCount(video.videoId);
                const latestComments = await getLatestComments(video.videoId);
                return { video, commentCount, latestComments };
            }));

            // 渲染视频列表
            videoItems.forEach(item => {
                const { video, commentCount } = item;
                const formatTime = (seconds) => {
                    const mins = Math.floor(seconds / 60);
                    const secs = Math.floor(seconds % 60);
                    return `${mins}:${secs.toString().padStart(2, '0')}`;
                };
                let coverUrl = video.coverUrl || "";
                coverUrl = coverUrl === "/bilibili/material/img/cover/null" 
                          ? "/bilibili/material/img/cover/default.jpg" 
                          : coverUrl;
                
                videoContainer.append(`
                    <div class="video-item">
                        <div class="video-thumb" style="background-image: url('${coverUrl}'); background-size: cover; background-position: center;">
                            <div class="video-duration">${formatTime(video.duration)}</div>
                        </div>
                        <div class="video-info">
                            <div class="video-title">${video.title}</div>
                            <div class="video-stats">
                                <div class="stat-item"><i class="fas fa-play"></i> ${video.viewCount}</div>
                                <div class="stat-item"><i class="fas fa-comment"></i> ${commentCount}</div>
                                <div class="stat-item"><i class="fas fa-heart"></i> ${video.likeCount}</div>
                            </div>
                        </div>
                    </div>
                `);
            });
        } catch (error) {
            console.error("获取视频数据失败:", error);
        }
    }

    async function showLatestComments() {
        try {
            const videoResponse = await $.ajax({
                type: "GET",
                url: "allVideo.do",
                error: () => {
                    console.error("获取视频列表失败");
                    return { data: [] };
                }
            });
            
            const videoIds = videoResponse.data.map(video => video.videoId);
            if (videoIds.length === 0) {
                console.log("没有视频数据，跳过评论加载");
                return;
            }
            
            // 并行获取所有视频的评论（优化版）
            const commentPromises = videoIds.map(videoId => 
                $.ajax({
                    type: "GET",
                    url: "threeComment.do",
                    data: { e: videoId },
                    timeout: 5000,
                    error: (xhr, status, err) => ({ data: [] })
                })
            );
            
            const allComments = await Promise.all(commentPromises);
            const mergedComments = allComments
                .flatMap(res => res.data || [])
                .filter(comment => comment.createTime)
                .sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
                .slice(0, 3);
            
            const commentsContainer = $(".right-column .video-list").first();
            if (mergedComments.length === 0) {
                commentsContainer.html(`
                    <div class="no-comments">暂无评论</div>
                `);
                return;
            }
            
            commentsContainer.empty();
            mergedComments.forEach(comment => {
                commentsContainer.append(`
                    <div class="video-item" style="border-left: 3px solid #00A1D6; padding-left: 10px;">
                        <div class="video-info">
                            <div class="video-title" style="font-weight: bold;">${comment.username}：${comment.content}</div>
                            <div class="video-stats" style="color: #999;">${formatDate(comment.createTime)} · 
                                <i class="fas fa-thumbs-up" style="margin-right: 5px;"></i>${comment.likeCount || 0}
                            </div>
                        </div>
                    </div>
                `);
            });
            
        } catch (error) {
            console.error("评论加载异常:", error);
        }
    }
    async function getLatestComments(videoId) {
        try {
            const response = await $.ajax({
                type: "GET",
                url: "threeComment.do",
                data: { e: videoId }
            });
            return response.data || [];
        } catch (error) {
            console.error("获取评论失败:", error);
            return [];
        }
    }
    function formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN');
    }

    // 页面加载完成后初始化所有功能
    document.addEventListener('DOMContentLoaded', function() {
        console.log('DOMContentLoaded事件触发');
        initFileUploads();
        initFormSubmit();
        initNavigation();
        initModal();
    });
    // 导航栏点击处理函数
    function handleNavClick(e) {
        const navItems = document.querySelectorAll('.nav-item');
        navItems.forEach(nav => nav.classList.remove('active'));
        this.classList.add('active');

        // 更新页面标题
        const title = this.querySelector('span').textContent;
        document.querySelector('.section-title').innerHTML =
            `<i class="${this.querySelector('i').className}"></i> ${title}`;
    }

    // 初始化模态框交互（防止重复绑定）
    function initModal() {
        if (isModalInitialized) return;

        const uploadBtn = document.getElementById('uploadBtn');
        const uploadModal = document.getElementById('uploadModal');
        const closeBtn = document.querySelector('.close-btn');

        $(uploadBtn).off('click.modal').on('click.modal', function () {
            uploadModal.style.display = 'flex';
            document.body.style.overflow = 'hidden';
        });

        $(closeBtn).off('click.modal').on('click.modal', function () {
            uploadModal.style.display = 'none';
            document.body.style.overflow = 'auto';
        });

        $(window).off('click.modal').on('click.modal', function (event) {
            if (event.target === uploadModal) {
                uploadModal.style.display = 'none';
                document.body.style.overflow = 'auto';
            }
        });

        isModalInitialized = true;
    }

    // 刷新评论列表
    function refreshComments() {
        selectAllComment();
    }
    function selectAllComment(pageNum) {
        $.ajax({
            url: "commentAllSix.do",
            type: "GET",
            data: {
            	action:"all",
            	pageNum:pageNum
            },
            success: function (data) {
            	console.log(data)
                comments = data.data;
                // 初始时设置过滤后的评论为全部评论
                filteredComments = data.data.data;
                // 应用当前排序
                sortComments(currentSort);
                updatePagination();
                showComments(currentPage);
            }
        });
    }

    // 搜索评论
    function searchComments(query) {
        if (!query) {
            // 如果搜索框为空，显示所有评论
            filteredComments = [...comments];
        } else {
            const lowerQuery = query.toLowerCase();
            filteredComments = comments.filter(comment => {
                // 搜索条件：评论内容、用户名或视频标题包含搜索词
                return comment.content.toLowerCase().includes(lowerQuery) || 
                       comment.username.toLowerCase().includes(lowerQuery) || 
                       (comment.videoTitle && comment.videoTitle.toLowerCase().includes(lowerQuery));
            });
        }
        // 应用当前排序
        sortComments(currentSort);
        // 重置到第一页
        currentPage = 1;
        updatePagination();
        showComments(currentPage);
    }

    // 排序评论
    function sortComments(sortType) {
        currentSort = sortType;
        if (sortType === 'newest') {
            // 最新优先：按创建时间降序排列
            filteredComments.sort((a, b) => new Date(b.createTime) - new Date(a.createTime));
        } else {
            // 最早优先：按创建时间升序排列
            filteredComments.sort((a, b) => new Date(a.createTime) - new Date(b.createTime));
        }
    }

    function showComments(page) {
        const startIndex = (page - 1) * itemsPerPage;
        const endIndex = startIndex + itemsPerPage;
        const currentComments = filteredComments.slice(startIndex, endIndex);
	console.log(currentComments)
        $('#comment-list').empty();

        for (let i = 0; i < currentComments.length; i++) {
            const comment = currentComments[i];
            const timestampMs = comment.createTime; // 13位毫秒级时间戳
            const dateFromMs = new Date(timestampMs).toLocaleDateString();
            // 假设这里有一个接口可以根据视频 ID 获取视频信息
            $.ajax({
                type: "GET",
                url: "video.do", // 替换为实际的接口地址
                data: { videoId: comment.videoId },
                success: function (videoData) {
                	console.log(videoData)
                    const videoTitle = videoData.title;
                    // 保存视频标题到评论对象，避免重复请求
                    comment.videoTitle = videoTitle;
                    $('#comment-list').append(`
                        <div class="comment-item">
                            <div class="comment-header">
                                <div class="comment-user">
                                    <div class="user-name">${comment.userName}</div>
                                </div>
                                <div class="comment-time">${dateFromMs}</div>
                            </div>
                            <div class="comment-content">
                                ${comment.content}
                            </div>
                            <div class="comment-source">
                                <i class="fas fa-video"></i>
                                <a href="#" class="source-link">${videoData.data[i].title}</a>
                            </div>
                            <div class="comment-actions">
                                <div class="comment-action delete" data-comment-id="${comment.commentId}">
                                    <i class="fas fa-trash-alt"></i> 删除
                                </div>
                            </div>
                        </div>
                    `);
                },
                error: function (xhr, status, error) {
                    console.error("获取视频信息失败:", error);
                    // 如果获取视频信息失败，使用默认标题并保存到评论对象
                    comment.videoTitle = "未知视频标题";
                    $('#comment-list').append(`
                        <div class="comment-item">
                            <div class="comment-header">
                                <div class="comment-user">
                                    <div class="user-name">${comment.username}</div>
                                </div>
                                <div class="comment-time">${comment.createTime}</div>
                            </div>
                            <div class="comment-content">
                                ${comment.content}
                            </div>
                            <div class="comment-source">
                                <i class="fas fa-video"></i>
                                <a href="#" class="source-link">未知视频标题</a>
                            </div>
                            <div class="comment-actions">
                                <div class="comment-action delete" data-comment-id="${comment.commentId}">
                                    <i class="fas fa-trash-alt"></i> 删除
                                </div>
                            </div>
                        </div>
                    `);
                }
            });
        }
    }

    function updatePagination() {
        const totalPages = Math.ceil(filteredComments.length / itemsPerPage);
        const pagination = $('#pagination');
        pagination.empty();

        if (totalPages > 1) {
            // 上一页按钮
            const prevButton = $('<button class="pagination-btn" id="prev-page"><i class="fas fa-chevron-left"></i></button>');
            if (currentPage === 1) {
                prevButton.addClass('disabled');
            }
            prevButton.on('click', function () {
                if (currentPage > 1) {
                    currentPage--;
                    showComments(currentPage);
                    updatePagination();
                }
            });
            pagination.append(prevButton);

            // 页码按钮
            for (let i = 1; i <= totalPages; i++) {
                const pageButton = $(`<button class="pagination-btn ${i === currentPage ? 'active' : ''}" data-page="${i}">${i}</button>`);
                pageButton.on('click', function () {
                    currentPage = parseInt($(this).data('page'));
                    showComments(currentPage);
                    updatePagination();
                });
                pagination.append(pageButton);
            }

            // 下一页按钮
            const nextButton = $('<button class="pagination-btn" id="next-page"><i class="fas fa-chevron-right"></i></button>');
            if (currentPage === totalPages) {
                nextButton.addClass('disabled');
            }
            nextButton.on('click', function () {
                if (currentPage < totalPages) {
                    currentPage++;
                    showComments(currentPage);
                    updatePagination();
                }
            });
            pagination.append(nextButton);
        }
    }

    function deleteComment(commentId) {
        if (confirm("确定要删除这条评论吗？")) {
            $.ajax({
                type: "POST",
                url: "deleteComment.do",
                data: { commentId: commentId },
                success: function (data) {
                    if (data.code === 200) {
                        alert("评论删除成功！");
                        // 从全局数组中移除已删除的评论
                        comments = comments.filter(comment => comment.commentId !== commentId);
                        // 更新过滤后的评论数组
                        filteredComments = filteredComments.filter(comment => comment.commentId !== commentId);
                        // 更新分页信息
                        updatePagination();
                        // 重新加载当前页评论
                        showComments(currentPage);
                    } else {
                        alert("评论删除失败：" + data.message);
                    }
                },
                error: function (xhr, status, error) {
                    console.error("请求出错:", error);
                    alert("请求出错：" + error);
                }
            });
        }
    }

    // 页面加载完成后初始化所有功能
    document.addEventListener('DOMContentLoaded', function () {
        console.log('DOMContentLoaded事件触发');
        initFileUploads();
        initFormSubmit();
        initNavigation();
        initModal();
        selectAllComment();

        // 为搜索输入框添加事件监听
        $('#commentSearch').on('input', function () {
            searchComments(this.value);
        });
        

        // 为排序下拉框添加事件监听
        $('#commentSort').on('change', function () {
            sortComments(this.value);
            // 重置到第一页
            currentPage = 1;
            updatePagination();
            showComments(currentPage);
        });

        // 使用事件委托处理删除按钮点击事件
        $('#comment-list').on('click', '.comment-action.delete', function () {
            const commentId = $(this).data("comment-id");
            deleteComment(commentId);
        });

        // 为刷新按钮添加事件监听
        $('#refresh-comments').on('click', refreshComments);
    });
    </script>
</body>

</html>